﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using RoadTeam.Model;
using RoadTeam.Enums;
using RoadTeam.SysInterface;
using RoadTeam.Pub;
using System.Collections.Specialized;

namespace RoadTeam.BLL
{
    public class CsMaintenanceDetailBll
    {
        private static object o = new object();

        public DataTable GetEmptyTable()
        {
            SqlWhere where = new SqlWhere();
            where.SelectColumn = @"  Top 0 * ";
            return CsMaintenanceDetail.Select(where, GlobalConfig.ConnectionString);
        }

        public void InsertMaintenanceDetail(DataTable Table_MainInfo, DataTable Table_DetailInfo)
        {
            String Identities = String.Empty;
            foreach (DataRow dr in Table_MainInfo.Rows)
            {
                Identities += "'" + dr["MaintenanceIdentities"].ToString() + "',";
            }
            if (String.IsNullOrEmpty(Identities)) return;
            DataTable Temp = FactoryClass.CreateCsMaintenance().GetMaintenanceByIdentities(Identities.TrimEnd(','));
            NameValueCollection value = new NameValueCollection();
            foreach (DataRow dr in Temp.Rows)
            {
                value.Add(dr[1].ToString(), dr[0].ToString());
            }


            DataRow dr_detail;
            String[] Strs = new string[] { }; ;
            String StrProjectIDs = String.Empty;
            List<string> liProjectID = new List<string>();
            String StrTemp;
            lock (o)
            {
                DataTable dt_detail = FactoryClass.CreateCsMaintenanceDetail().GetEmptyTable();
                foreach (DataRow dr in Table_DetailInfo.Rows)
                {
                    //MaintenanceID,ProjectID,OrganID,CreateDateTime,App_Identifier
                    dr_detail = dt_detail.NewRow();
                    Strs = value.GetValues(dr["MainIdentifier"].ToString());
                    if (Strs==null || Strs.Count() == 0) continue;
                    dr_detail[0] = Strs[0];
                    StrTemp = FactoryClass.CreateCsProject().GetIDByIdentitifer(dr["ProjectIdentitfier"].ToString());
                    dr_detail[1] = StrTemp;
                    if (!String.IsNullOrEmpty(StrTemp) && !liProjectID.Contains(StrTemp)) liProjectID.Add(StrTemp);
                    dr_detail[2] = FactoryClass.CreateSmOrgan().GetOraganID(dr["OrganIdentifier"].ToString());
                    dr_detail[3] = dr["CreateDateTime"];
                    dr_detail[4] = dr["MainDetailIdentifier"];
                    dt_detail.Rows.Add(dr_detail);
                }
                FactoryClass.CreateCsMaintenanceDetail().InsertCsMaintenanceDetail(dt_detail, liProjectID);
            }
            CsMaintenanceDetail.InsertDatatable(Table_DetailInfo, GlobalConfig.ConnectionString);
        }
    }
}
